local rtk=require('libluartk')
require 'games.heroes3.h3maprw'

local function xmlDump(t,file,encoding)
	local fh=io.open(file,'wt')
	assert(fh,'Unable open '..file..' for write')
	fh:write(string.format('<?xml version="1.0" encoding="%s"?>',encoding or "UTF-8"))
	fh:write('<Map>\n')
	fh:write(rtk.tableToXml(t))
	fh:write('</Map>')
	fh:close()
	rtk.dbg_print('XML dmped to %s\n',file)
end

local function luaDump(map,file)
	local fh=io.open(file,'wt')
	assert(fh,'Unable open '..file..' for write')
	fh:write('map=')
	fh:write(rtk.tableToLuaCode(map))
	fh:close()
	rtk.dbg_print('Lua dmped to %s\n',file)
end

local function dumpTest()
	local data
	local file=arg[1]
	data=readfile(file)
	local ast
	g_map_info=MapInfo:match(data)
	rtk.dbg_print('MapInfo=%s\n',rtk.tableToLuaCode(g_map_info))
	--ast=HeroConfigurationCustomizations:match(data,0x80a+1)
	--ast,pos=(Terrain * Cp()):match(data,0xce3+1)
	--ast=Ct(TerrainTile ^ -5):match(data,0xce3+1)
	local t0,t1
	t0=rtk.time_mark()
	ast,pos=(h3m * Cp() * -1):match(data)
	t1=rtk.time_mark()
	rtk.printk(2,'Map %s loaded in %.3f ms.\n',file,(t1-t0)*1000)
	ast.mapFile=rtk.iconv('gbk','utf-8',file)
	--ast=ast.allHeroes
	--ast={ast.mapObjectTemplates,ast.mapObjects}
	local function test_temp()
		globals.mapObjectTemplates=MapObjectTemplates:match(data,0x11d0f-4+1)
		ast,pos=(MapObject*Cp()):match(data,0x12596+1)
	end
	--test_temp()
	--ast,pos=(MapObjectSeersHut * Cp()):match(data,0x1270e+1)
	--ast={objects=ast.mapObjects,temps=ast.mapObjectTemplates}
	--ast=ast.mapObjects
	--ast,pos=(Ct(MapObjectTemplate^-5) * Cp()):match(data,0x47ae7+1)
	--ast,pos=(AllowedSpells * Cp()):match(data,0x7bf+1)
	--ast,pos=(AllowedSecodarySkills * Cp()):match(data,0x7c8+1)
	rtk.dbg_print('EndPos=0x%x',pos-1)
	if rtk.getprop('xml') then
		xmlDump(ast,rtk.getprop('xml'),'UTF-8')
	end
	if rtk.getprop('lua') then
		luaDump(ast,rtk.getprop('lua'))
	end
end

local function dump_h3m(file)
	local t0,t1
	t0=rtk.time_mark()
	local ast,err=h3MapReadFile(file)
	t1=rtk.time_mark()
	if ast then
		rtk.printk(2,'%s loaded in %.3f ms.\n',file,(t1-t0)*1000)
	else
		rtk.printk(2,'Error loading : %s\n%s\n',file,err)
		return
	end
	if rtk.getprop('xml') then
		xmlDump(ast,rtk.getprop('xml'),'UTF-8')
	end
	if rtk.getprop('lua') then
		luaDump(ast,rtk.getprop('lua'))
	end
end

function main(self,...)
	local _,f
	rtk.tprint{...}
	for _,f in ipairs({...}) do
	print(f)
		dump_h3m(f)
	end
end

if not rtk.getpropFlag('#.startAsExe') then
	main('h3mdump',...)
end